
    /**  
    * @Title: LogStorageMongoConfiguration.java
    * @Package com.efast.cafe.commponent.log.configuration
    * @Description: TODO(用一句话描述该文件做什么)
    * @author Administrator
    * @date 2018年9月4日
    * @version V1.0  
    */
    
package com.efast.cafe.commponent.log.configuration;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

import com.efast.cafe.commponent.log.constant.LogConstant;
import com.efast.cafe.util.ConfigUtil;
import com.efast.cafe.util.StringUtil;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

/**
    * @ClassName: LogStorageMongoConfiguration
    * @Description: 日志服务启用mongodb配置
    * @author Administrator
    * @date 2018年9月4日
    *
    */
@ConditionalOnProperty(
        name=LogConstant.K_STORAGE,
        havingValue="mongodb"
)
@Configuration
@AutoConfigureAfter(MongoPropertiesConfiguration.class)
public class LogStorageMongoConfiguration {
	private String storage = ConfigUtil.getValue(LogConstant.K_STORAGE);
	
	@Autowired
	private MongoPropertiesConfiguration mongoSettingsProperties;
	
	
	
	@Bean("logMongoTemplate")
	public MongoTemplate mongoTemplate(){
		if(storage.equals("mongodb")){
			MongoTemplate template = new MongoTemplate(mongoDbFactory());
			return template;
		}
		return null;
	}
	
	public MongoDbFactory mongoDbFactory() {
		 //客户端配置（连接数、副本集群验证）
		  MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
		  builder.connectionsPerHost(mongoSettingsProperties.getMaxConnectionPerHost());
		  builder.minConnectionsPerHost(mongoSettingsProperties.getMinConnectionPerHost());
		  builder.sslInvalidHostNameAllowed(false);
		  builder.threadsAllowedToBlockForConnectionMultiplier(mongoSettingsProperties.getThreadsAllowedToBlockForConnectionMultiplier());
		  builder.maxWaitTime(mongoSettingsProperties.getMaxWaitTime());
		  builder.serverSelectionTimeout(mongoSettingsProperties.getServerSelectionTimeout());
		  builder.connectTimeout(mongoSettingsProperties.getConnectTimeout());
		  builder.sslEnabled(mongoSettingsProperties.getSslEnabled());
		  if (StringUtil.isNotBlank(mongoSettingsProperties.getReplicaSet())) {
		   builder.requiredReplicaSetName(mongoSettingsProperties.getReplicaSet());
		  }
		  MongoClientOptions mongoClientOptions = builder.build();
		 
		  // MongoDB地址列表
		  List<ServerAddress> serverAddresses = new ArrayList<>();
		  for (String host : mongoSettingsProperties.getHosts()) {
		   Integer index = mongoSettingsProperties.getHosts().indexOf(host);
		   Integer port = mongoSettingsProperties.getPorts().get(index);
		 
		   ServerAddress serverAddress = new ServerAddress(host, port);
		   serverAddresses.add(serverAddress);
		  }
		  System.out.println("serverAddresses:" + serverAddresses.toString());
		 
		  // 连接认证
		  List<MongoCredential> mongoCredentialList = new ArrayList<>();
		  if (mongoSettingsProperties.getUsername() != null) {
		   mongoCredentialList.add(MongoCredential.createScramSha1Credential(
		     mongoSettingsProperties.getUsername(),
		     mongoSettingsProperties.getAuthenticationDatabase() != null ? mongoSettingsProperties.getAuthenticationDatabase() : mongoSettingsProperties.getDatabase(),
		     mongoSettingsProperties.getPassword().toCharArray()));
		  }
		  System.out.println("mongoCredentialList:" + mongoCredentialList.toString());
		  //创建客户端和Factory
		  MongoClient mongoClient = null;
		  if(serverAddresses.size()==1)
			  mongoClient = new MongoClient(serverAddresses.get(0), mongoCredentialList,mongoClientOptions);
		  else
			  mongoClient = new MongoClient(serverAddresses, mongoCredentialList, mongoClientOptions);
		  
		  MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, mongoSettingsProperties.getDatabase());
		  return mongoDbFactory;
	}
}
